package com.pro_one.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pro_one.constant.QiniuConstant;
import com.pro_one.constant.RedisConstant;
import com.pro_one.dao.OrderDao;
import com.pro_one.dao.SetmealDao;
import com.pro_one.entity.PageResult;
import com.pro_one.entity.QueryPageBean;
import com.pro_one.pojo.CheckGroup;
import com.pro_one.pojo.Setmeal;
import com.pro_one.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional(readOnly = true)
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outputpath;

    @Override
    public List<Map<String, Object>> findMoneyCountBySetmeal(List<String> orderDay) {
        //收入    名称     多少钱
        List<Map<String, Object>>  setmealMoneyCount = new ArrayList<>();

        //遍历
        for (String order : orderDay) {
            //收入
            setmealMoneyCount.addAll(setmealDao.setmealMoneyCount(order));
            //将查到的收入与名称放入集合
            //setmealMoneyCount.add(MoneyCount);
        }
        return setmealMoneyCount;
    }



    /**
     * 套餐列表查询，以及根据条件查询
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findByCondition(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        List<Setmeal> setmeals = setmealDao.findByCondition(queryString);
        PageInfo pageInfo = new PageInfo(setmeals);
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 添加套餐
     *
     * @param setmeal
     * @param checkgroupIds
     */
    @Override
    @Transactional(readOnly = false)
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        String img = setmeal.getImg();
        if (img != null) {
            String imgName = img.substring(QiniuConstant.UPLOAD_URL.length());
            setmeal.setImg(imgName);
        }
        setmealDao.addSetmeal(setmeal);
        for (Integer checkgroupId : checkgroupIds) {
            setmealDao.addGroupIdAndSetmealId(checkgroupId, setmeal.getId());
        }
        if (img != null) {
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
        }
        this.generateHtml();
    }

    /**
     * 生成静态页面
     */
    public void generateHtml() {
        List<Setmeal> list = setmealDao.findAllGroupAndItem();
        generateListStaicHtml(list);
        generateDetailStaticHtml(list);
    }

    /**
     * 生成套餐列表静态页面的方法
     */
    public void generateListStaicHtml(List<Setmeal> list) {
        Map map = new HashMap();
        for (Setmeal setmeal : list) {
            setmeal.setImg(QiniuConstant.UPLOAD_URL + setmeal.getImg());
        }
        map.put("setmealList", list);
        generateStaticHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    /**
     * 生成套餐详情静态页面的方法
     *
     * @param
     */
    public void generateDetailStaticHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal", setmeal);
            generateStaticHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }

    /**
     * 通用的生成静态页面方法
     *
     * @param template
     * @param htmlName
     * @param map
     */
    public void generateStaticHtml(String template, String htmlName, Map map) {
        Writer writer = null;
        try {
            Configuration configuration = freeMarkerConfigurer.getConfiguration();
            Template template1 = configuration.getTemplate(template);
            writer = new OutputStreamWriter(new FileOutputStream(outputpath + "/" + htmlName), "UTF-8");
            template1.process(map, writer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 根据id查询检查套餐
     *
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealDao.findById(id);
        if (setmeal != null) {
            setmeal.setImg(QiniuConstant.UPLOAD_URL + setmeal.getImg());
        }
        return setmeal;

    }

    /**
     * 根据套餐id查询所有检查组
     *
     * @param queryPageBean
     * @param id
     * @return
     */
    @Override
    public PageResult findAllGroupsByMealId(QueryPageBean queryPageBean, Integer id) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        List<CheckGroup> checkGroups = setmealDao.findAllGroupsByMealId(id);
        PageInfo pageInfo = new PageInfo(checkGroups);
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 根据中间表查询所有检查组
     *
     * @param id
     * @return
     */
    @Override
    public List<Integer> findAssociations(Integer id) {
        List<Integer> associations = setmealDao.findAssociations(id);
        return associations;
    }

    /**
     * 修改检查套餐以及关联的检查组信息
     *
     * @param setmeal
     * @param checkgroupIds
     */
    @Override
    @Transactional(readOnly = false)
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        Integer id = setmeal.getId();
        String oldImg = setmealDao.findById(id).getImg();
        String newImg = setmeal.getImg();
        if (oldImg != null) {
            if (!oldImg.equals(newImg)) {
                String finalImgName = newImg.substring(QiniuConstant.UPLOAD_URL.length());
                setmeal.setImg(finalImgName);
                jedisPool.getResource().smove(RedisConstant.SETMEAL_PIC_DB_RESOURCES, RedisConstant.SETMEAL_PIC_RESOURCES, oldImg);
                jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, finalImgName);
            }
        }
        setmealDao.edit(setmeal);
        setmealDao.deleteGroupIdByMealId(id);
        for (Integer checkgroupId : checkgroupIds) {
            setmealDao.addGroupIdAndSetmealId(checkgroupId, id);
        }
    }

    /**
     * 删除检查套餐以及检查组
     *
     * @param id
     */
    @Override
    @Transactional(readOnly = false)
    public void deleteAllByMealId(Integer id) {
        Setmeal setmeal = setmealDao.findById(id);
        String img = setmeal.getImg();
        if (img != null) {
            jedisPool.getResource().smove(RedisConstant.SETMEAL_PIC_DB_RESOURCES, RedisConstant.SETMEAL_PIC_RESOURCES, img);
        }
        List<Integer> groupIds = this.findAssociations(id);
        if (groupIds != null && groupIds.size() > 0) {
            setmealDao.deleteGroupIdByMealId(id);
        }
        setmealDao.deleteById(id);
    }

    /**
     * 普通查询所有套餐列表
     *
     * @return
     */
    @Override
    public List<Setmeal> getSetmeal() {
        List<Setmeal> setmeals = setmealDao.findAll();
        for (Setmeal setmeal : setmeals) {
            setmeal.setImg(QiniuConstant.UPLOAD_URL + setmeal.getImg());
        }
        return setmeals;
    }

    /**
     * 瀑布流分页查询套餐列表
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult getSetmeal(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        List<Setmeal> setmeals = setmealDao.findAll();
        for (Setmeal setmeal : setmeals) {
            setmeal.setImg(QiniuConstant.UPLOAD_URL + setmeal.getImg());
        }
        PageInfo pageInfo = new PageInfo<>(setmeals);
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 展示页面套餐数据的饼图
     *
     * @return
     */
    @Override
    public Map getSetmealReport() {
        List<Map<String, Object>> setmealCount = setmealDao.getSetmealCount();
        List<String> setmealNames = new ArrayList<>();
        for (Map<String, Object> map : setmealCount) {
            setmealNames.add((String) map.get("name"));
        }
        Map map = new HashMap();
        map.put("setmealNames", setmealNames);
        map.put("setmealCount", setmealCount);
        return map;
    }

    @Override
    public List<Map<String, String>> findAllOptions3() {
        List<String> list = setmealDao.findAllOptions3();
        List<Map<String,String>> findAll = new ArrayList<>();
        for (String s : list) {
            Map<String,String> map = new HashMap<>();
            map.put("setmealName",s);
            map.put("label",s);
            findAll.add(map);
        }
        return findAll;
    }

    @Override
    public PageResult findByCondition1(QueryPageBean queryPageBean, Integer id) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        List<Setmeal> setmeals = setmealDao.findByCondition1(id);
        PageInfo pageInfo = new PageInfo(setmeals);
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }


}
